<template>
  <div>
    <div style="padding: 10px">
      <el-card>
        <div class="body">
          <elform2
            :searchData="searchData"
            :status="status"
            :label="'关键字'"
            :newwhat="'新增技巧'"
            :placeholder="'根据关键字搜索'"
            @resetField="resetField"
            @search="search"
            @add="add"
          ></elform2>

          <elalert :counts="counts"></elalert>

          <el-table :data="list" style="width: 100%">
            <el-table-column type="index" label="序号" width="80px" />
            <el-table-column prop="title" label="文章标题" width="400" />
            <el-table-column prop="visits" label="阅读数" />
            <el-table-column prop="username" label="录入人" />
            <el-table-column prop="createTime" label="录入时间" />
            <el-table-column prop="state" label="状态" width="100" />
            <el-table-column label="操作" width="180" class="btncell">
              <template #default="{ row }">
                <el-button type="text" @click="view(row)"> 预览</el-button>
                <el-button type="text" @click="forbidden(row)">
                  {{ row.state === '已启用' ? '禁用' : '启用' }}</el-button
                >
                <el-button
                  type="text"
                  @click="edit(row)"
                  :disabled="row.state === '已启用' ? true : false"
                  >修改
                </el-button>
                <el-button
                  type="text"
                  style="margin-left: 9px"
                  @click="del(row)"
                >
                  删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>

          <elpagination
            :counts="counts"
            :data="searchData"
            :n="[5, 10, 20, 50]"
            @handleSizeChange="handleSizeChange"
            @handleCurrentChange="handleCurrentChange"
          ></elpagination>
        </div>
      </el-card>
    </div>
    <!-- 添加、修改的弹窗 -->
    <el-dialog
      :visible.sync="showDialog"
      width="800px"
      :title="title"
      @close="closeDialog"
    >
      <el-form
        ref="addRef"
        :model="dialogData"
        :rules="rules"
        v-if="title !== '预览文章'"
      >
        <el-form-item label="文章标题：" label-width="100px" prop="title">
          <el-input
            placeholder="请输入文章标题"
            v-model="dialogData.title"
          ></el-input>
        </el-form-item>

        <el-form-item label="文章内容：" label-width="100px" prop="articleBody">
          <quillEditor
            v-model="dialogData.articleBody"
            :options="editorOptions"
            style="height: 200px; margin-bottom: 40px"
          ></quillEditor>
        </el-form-item>

        <el-form-item label="视频地址：" label-width="100px" prop="videoURL">
          <el-input
            v-model="dialogData.videoURL"
            placeholder="请输入视频地址"
          ></el-input>
        </el-form-item>
      </el-form>

      <div align="center" v-if="title !== '预览文章'">
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="submitCheck">确认</el-button>
      </div>

      <div v-if="this.title === '预览文章'" class="view">
        <h2>{{ dialogData.title }}</h2>
        <div>
          <span>{{ dialogData.createTime }}</span>
          <span>{{ dialogData.username }}</span>
          <span class="el-icon-view"></span>
          <span>{{ dialogData.visits }}</span>
        </div>
        <div class="content" v-html="dialogData.articleBody"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects'
import { list, remove, update, add, changeState } from '@/api/hmmm/articles'
import elalert from '@/components/elalert'
import elpagination from '@/components/elpagination/index.vue'
import elform2 from '@/components/form2'
import { status } from '@/api/hmmm/constants'
import { quillEditor } from 'vue-quill-editor'
import moment from 'moment'
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'], // 加粗 斜体 下划线 删除线
  [{ list: 'ordered' }, { list: 'bullet' }], // 有序、无序列表
  ['blockquote', 'code-block'],
  ['image', 'link']
]
export default {
  data() {
    return {
      counts: 0,
      status: status,
      subjectID: [],
      searchData: {
        keyword: '',
        page: 1,
        pagesize: 10,
        state: null
      },
      editorOptions: {
        theme: 'snow',
        placeholder: '',
        modules: {
          toolbar: toolbarOptions
        }
      },
      list: [],
      showDialog: false,
      title: '新增学科',
      dialogData: {
        title: '',
        id: null,
        articleBody: '',
        videoURL: null
      },
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        articleBody: [
          { required: true, message: '请输入文章内容', trigger: 'blur' }
        ]
      },
      artArr: [],
      artArr2: []
    }
  },
  components: { elalert, elpagination, elform2, quillEditor },
  created() {
    this.searchData.subjectID = this.$route.query.id
    this.getSimple()
    this.getArticleList()
  },
  methods: {
    async getArticleList() {
      const { data } = await list(this.searchData)
      data.items.forEach(item => {
        item.isFrontDisplay = item.isFrontDisplay === 1 ? '是' : '否'
        item.createTime = moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')
        item.state = item.state === 1 ? '已启用' : '已禁用'
      })
      if (JSON.parse(localStorage.getItem('artArr'))) {
        data.items.forEach(item => {
          JSON.parse(localStorage.getItem('artArr')).forEach(item2 => {
            item.id === item2.id ? (item.state = item2.state) : ''
          })
        })
      }
      this.list = data.items
      this.counts = data.counts
      this.searchData.page = data.page
      this.searchData.pagesize = data.pagesize
    },
    async getSimple() {
      const { data } = await simple()
      this.subjectID = data
    },
    resetField() {
      this.$refs.searchRef.resetFields()
    },
    handleSizeChange(val) {
      this.searchData.pagesize = val
      this.getArticleList()
    },
    handleCurrentChange(val) {
      this.searchData.page = val
      this.getArticleList()
    },
    search() {
      this.getArticleList()
    },
    add() {
      this.title = '新增文章'
      this.showDialog = true
    },
    async edit(row) {
      console.log(row)
      this.dialogData.id = row.id
      this.dialogData.title = row.title
      this.dialogData.articleBody = row.articleBody
      this.title = '修改文章'
      this.showDialog = true
    },
    async submitCheck() {
      try {
        await this.$refs.addRef.validate()
        if (this.title === '新增文章') {
          await add(this.dialogData)
          this.showDialog = false
          this.$message.success('添加成功')
          this.getArticleList()
        } else if (this.title === '修改文章') {
          await update(this.dialogData)
          this.showDialog = false
          this.$message.success('修改成功')
          this.getArticleList()
        }
      } catch (error) {
        console.log(error)
      }
    },
    closeDialog() {
      this.$refs.addRef.resetFields()
    },
    async forbidden(row) {
      row.state = row.state === '已启用' ? 1 : 0
      await changeState({ id: row.id, state: row.state })
      this.$message.success('操作成功')
      row.state = row.state === 0 ? '已启用' : '已禁用'
      this.list.forEach(item => {
        this.artArr.push({ id: item.id, state: item.state })
      })
      localStorage.setItem('artArr', JSON.stringify(this.artArr))
    },
    view(row) {
      this.title = '预览文章'
      this.dialogData = { ...row }
      console.log(this.dialogData)
      this.showDialog = true
    },
    async del(row) {
      this.$confirm('该项操作不可恢复！确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          await remove(row)
          this.$message.success('删除成功')
          this.getArticleList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除'
          })
        })
    }
  }
}
</script>

<style scoped lang="scss">
.el-card {
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  border: 1px solid #ebeef5;
  background-color: #fff;
  color: #303133;
  -webkit-transition: 0.3s;
  transition: 0.3s;
  border-radius: 4px;
  overflow: hidden;
  .body {
    width: 100%;
    -webkit-font-smoothing: antialiased;
    text-rendering: optimizeLegibility;
    font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
      Microsoft YaHei, Arial, sans-serif;

    ::v-deep .el-table {
      .el-table--fit {
        border-right: 0;
        border-bottom: 0;
      }
    }
    ::v-deep .el-table th.el-table__cell.is-leaf {
      border-bottom: 2px solid #e8e8e8;
      background-color: #fafafa;
    }
    ::v-deep .el-card .body[data-v-eacc1416] .el-table td.el-table__cell div {
      display: flex;
      padding-left: 5px;
      padding-right: 5px;
      box-sizing: border-box;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: normal;
      word-break: break-all;
      line-height: 23px;
    }
  }
}
::v-deep .el-dialog {
  .el-form {
    .el-form-item {
      margin-bottom: 18px;
      .ql-toolbar.ql-snow {
        padding: 0 8px;
      }
    }
  }

  .view {
    h2 {
      margin: 0;
    }
    span {
      margin-left: 10px;
      margin: 10px 0;
    }
    .content {
      background: #f5f5f5;
      border-top: 1px dashed #ccc;
      padding: 10px;
    }
  }
}
</style>
